Skip to content

Conversation

@vishwab1
Copy link
Member

@vishwab1 vishwab1 commented May 26, 2025

📋 Description

JIRA ID:

Please provide a summary of the change and the motivation behind it. Include relevant context and details.


Added cors orign method to restrict from the browsers

✅ Type of Change

  • 🐞 Bug fix (non-breaking change which resolves an issue)
  • New feature (non-breaking change which adds functionality)
  • 🔥 Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • 🛠 Refactor (change that is neither a fix nor a new feature)
  • ⚙️ Config change (configuration file or build script updates)
  • 📚 Documentation (updates to docs or readme)
  • 🧪 Tests (adding new or updating existing tests)
  • 🎨 UI/UX (changes that affect the user interface)
  • 🚀 Performance (improves performance)
  • 🧹 Chore (miscellaneous changes that don't modify src or test files)

ℹ️ Additional Information

Please describe how the changes were tested, and include any relevant screenshots, logs, or other information that provides additional context.

Summary by CodeRabbit

  • New Features
    • Added centralized configuration for allowed CORS origins, enabling flexible cross-origin access control.
    • Introduced enhanced handling of CORS requests, including support for preflight (OPTIONS) requests and dynamic origin validation.
  • Refactor
    • Removed individual CORS annotations from all controllers to consolidate CORS management.
    • Updated filters to support and enforce the new CORS configuration.
  • Chores
    • Updated configuration files to include new CORS-related properties.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 26, 2025

Walkthrough

This change centralizes CORS (Cross-Origin Resource Sharing) configuration by removing all @CrossOrigin annotations from controller classes and methods, introducing a global CORS configuration via CorsConfig and a dynamic filter. Configuration properties for allowed origins are added, and filters are updated to handle CORS headers and preflight requests.

Changes

File(s) Change Summary
src/main/environment/common_ci.properties, src/main/environment/common_example.properties Added cors.allowed-origins property for CORS configuration.
src/main/java/com/wipro/fhir/config/CorsConfig.java Added new global CORS configuration class using WebMvcConfigurer.
src/main/java/com/wipro/fhir/utils/DynamicCorsFilter.java Introduced dynamic CORS filter to handle allowed origins and CORS headers.
src/main/java/com/wipro/fhir/utils/FilterConfig.java Injected cors.allowed-origins property and passed it to JWT filter.
src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java Enhanced to handle CORS headers, allowed origins, and preflight OPTIONS requests.
src/main/java/com/wipro/fhir/controller/.../*.java (multiple controller files) Removed all @CrossOrigin annotations from classes and methods.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant DynamicCorsFilter
    participant JwtUserIdValidationFilter
    participant CorsConfig
    participant Controller

    Client->>DynamicCorsFilter: HTTP Request (with Origin header)
    DynamicCorsFilter->>DynamicCorsFilter: Check allowed origins
    alt Origin allowed
        DynamicCorsFilter->>Client: Set CORS headers
    end
    alt OPTIONS request
        DynamicCorsFilter->>Client: Respond 200 OK (preflight)
    else
        DynamicCorsFilter->>JwtUserIdValidationFilter: Forward request
        JwtUserIdValidationFilter->>JwtUserIdValidationFilter: Set CORS headers, validate JWT
        JwtUserIdValidationFilter->>Controller: Forward request if valid
        Controller->>Client: Response
    end
Loading

Possibly related PRs

  • PSMRI/FHIR-API#84: Modifies JwtUserIdValidationFilter for JWT validation logic; both PRs touch the same filter class, but this PR focuses on CORS support and preflight handling.

Suggested reviewers

  • ravishanigarapu

Poem

A hop and a skip, CORS rules take flight,
No more annotations cluttering the night.
Filters and configs now handle the chore,
Allowed origins set—no less, no more.
Spring controllers breathe a sigh of relief,
As cross-origin calls are handled with ease!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@sonarqubecloud
Copy link

Quality Gate Failed Quality Gate failed

Failed conditions
11.9% Duplication on New Code (required ≤ 3%)

See analysis details on SonarQube Cloud

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🧹 Nitpick comments (7)
src/main/java/com/wipro/fhir/controller/test/Test.java (1)

45-45: Removed redundant controller-level @CrossOrigin annotation.
This aligns with the new global CORS setup; please remove the now-unused CrossOrigin import to clean up the code.

src/main/java/com/wipro/fhir/controller/healthIDvalidate/HealthIDValidateController.java (1)

27-27: Clean up unused import.

The @CrossOrigin import is no longer needed since all annotations have been removed as part of the CORS centralization.

-import org.springframework.web.bind.annotation.CrossOrigin;
src/main/java/com/wipro/fhir/controller/carecontext/CareContextController.java (1)

27-27: Clean up unused import.

The @CrossOrigin import is no longer needed since all annotations have been removed.

-import org.springframework.web.bind.annotation.CrossOrigin;
src/main/java/com/wipro/fhir/controller/healthID/CreateHealthIDWithMobileOTP.java (1)

28-28: Clean up unused import.

The @CrossOrigin import is no longer needed.

-import org.springframework.web.bind.annotation.CrossOrigin;
src/main/java/com/wipro/fhir/controller/generateresource/ResourceRequestGateway.java (1)

27-27: Clean up unused import.

The @CrossOrigin import is no longer needed.

-import org.springframework.web.bind.annotation.CrossOrigin;
src/main/java/com/wipro/fhir/controller/v3/abha/CreateAbhaV3Controller.java (1)

6-6: Remove unused import.

The @CrossOrigin import is no longer needed since the annotations have been removed.

-import org.springframework.web.bind.annotation.CrossOrigin;
src/main/java/com/wipro/fhir/controller/healthCard/GenerateHealthIDCardController.java (1)

27-27: Remove unused import.

The @CrossOrigin import is no longer needed since the annotations have been removed.

-import org.springframework.web.bind.annotation.CrossOrigin;
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 75b6f91 and 35d8a7a.

📒 Files selected for processing (21)
  • src/main/environment/common_ci.properties (1 hunks)
  • src/main/environment/common_example.properties (1 hunks)
  • src/main/java/com/wipro/fhir/config/CorsConfig.java (1 hunks)
  • src/main/java/com/wipro/fhir/controller/carecontext/CareContextController.java (3 hunks)
  • src/main/java/com/wipro/fhir/controller/eaushdhi/EAushadhiController.java (5 hunks)
  • src/main/java/com/wipro/fhir/controller/facility/FacilityController.java (3 hunks)
  • src/main/java/com/wipro/fhir/controller/generateresource/ResourceRequestGateway.java (4 hunks)
  • src/main/java/com/wipro/fhir/controller/healthCard/GenerateHealthIDCardController.java (2 hunks)
  • src/main/java/com/wipro/fhir/controller/healthID/CreateHealthIDWithBio.java (4 hunks)
  • src/main/java/com/wipro/fhir/controller/healthID/CreateHealthIDWithMobileOTP.java (5 hunks)
  • src/main/java/com/wipro/fhir/controller/healthID/CreateHealthIDWithUID.java (6 hunks)
  • src/main/java/com/wipro/fhir/controller/healthID/CreateHealthIdRecord.java (3 hunks)
  • src/main/java/com/wipro/fhir/controller/healthIDvalidate/HealthIDValidateController.java (3 hunks)
  • src/main/java/com/wipro/fhir/controller/patientdatahandler/HigherHealthFacilityController.java (2 hunks)
  • src/main/java/com/wipro/fhir/controller/patientdatahandler/PatientDataGatewayController.java (3 hunks)
  • src/main/java/com/wipro/fhir/controller/test/Test.java (2 hunks)
  • src/main/java/com/wipro/fhir/controller/v3/abha/CreateAbhaV3Controller.java (5 hunks)
  • src/main/java/com/wipro/fhir/controller/v3/abha/LoginAbhaV3Controller.java (4 hunks)
  • src/main/java/com/wipro/fhir/utils/DynamicCorsFilter.java (1 hunks)
  • src/main/java/com/wipro/fhir/utils/FilterConfig.java (1 hunks)
  • src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java (4 hunks)
🧰 Additional context used
🧠 Learnings (5)
src/main/java/com/wipro/fhir/controller/v3/abha/LoginAbhaV3Controller.java (1)
Learnt from: helenKaryamsetty
PR: PSMRI/FHIR-API#52
File: src/main/java/com/wipro/fhir/controller/v3/abha/LoginAbhaV3Controller.java:18-20
Timestamp: 2024-12-09T16:09:31.513Z
Learning: In the Java Spring Boot project, all controllers, including `LoginAbhaV3Controller.java` at `src/main/java/com/wipro/fhir/controller/v3/abha/`, use the `@CrossOrigin` annotation without parameters to maintain consistency across the codebase.
src/main/java/com/wipro/fhir/controller/facility/FacilityController.java (1)
Learnt from: helenKaryamsetty
PR: PSMRI/FHIR-API#52
File: src/main/java/com/wipro/fhir/controller/v3/abha/LoginAbhaV3Controller.java:18-20
Timestamp: 2024-12-09T16:09:31.513Z
Learning: In the Java Spring Boot project, all controllers, including `LoginAbhaV3Controller.java` at `src/main/java/com/wipro/fhir/controller/v3/abha/`, use the `@CrossOrigin` annotation without parameters to maintain consistency across the codebase.
src/main/java/com/wipro/fhir/controller/patientdatahandler/PatientDataGatewayController.java (1)
Learnt from: helenKaryamsetty
PR: PSMRI/FHIR-API#52
File: src/main/java/com/wipro/fhir/controller/v3/abha/LoginAbhaV3Controller.java:18-20
Timestamp: 2024-12-09T16:09:31.513Z
Learning: In the Java Spring Boot project, all controllers, including `LoginAbhaV3Controller.java` at `src/main/java/com/wipro/fhir/controller/v3/abha/`, use the `@CrossOrigin` annotation without parameters to maintain consistency across the codebase.
src/main/java/com/wipro/fhir/controller/v3/abha/CreateAbhaV3Controller.java (1)
Learnt from: helenKaryamsetty
PR: PSMRI/FHIR-API#52
File: src/main/java/com/wipro/fhir/controller/v3/abha/LoginAbhaV3Controller.java:18-20
Timestamp: 2024-12-09T16:09:31.513Z
Learning: In the Java Spring Boot project, all controllers, including `LoginAbhaV3Controller.java` at `src/main/java/com/wipro/fhir/controller/v3/abha/`, use the `@CrossOrigin` annotation without parameters to maintain consistency across the codebase.
src/main/java/com/wipro/fhir/controller/healthCard/GenerateHealthIDCardController.java (1)
Learnt from: helenKaryamsetty
PR: PSMRI/FHIR-API#52
File: src/main/java/com/wipro/fhir/controller/v3/abha/LoginAbhaV3Controller.java:18-20
Timestamp: 2024-12-09T16:09:31.513Z
Learning: In the Java Spring Boot project, all controllers, including `LoginAbhaV3Controller.java` at `src/main/java/com/wipro/fhir/controller/v3/abha/`, use the `@CrossOrigin` annotation without parameters to maintain consistency across the codebase.
🧬 Code Graph Analysis (1)
src/main/java/com/wipro/fhir/config/CorsConfig.java (1)
src/main/java/com/wipro/fhir/utils/FilterConfig.java (1)
  • Configuration (9-27)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (java)
🔇 Additional comments (25)
src/main/environment/common_ci.properties (1)

118-118: Add cors.allowed-origins placeholder for CI environment.
This introduces the central CORS origins configuration; ensure that the CORS_ALLOWED_ORIGINS environment variable is defined in your CI settings and that its value is injected correctly at build time.

src/main/environment/common_example.properties (1)

114-115: Define default allowed origins in example config.
The pattern http://localhost:* may not be recognized by Spring’s allowedOrigins (which expects exact matches). Verify whether your CorsConfig uses allowedOriginPatterns for wildcard support or adjust this to an explicit list of ports.

src/main/java/com/wipro/fhir/controller/patientdatahandler/HigherHealthFacilityController.java (2)

37-37: Removed class-level @CrossOrigin annotation.
Ensure that the global CORS configuration (via CorsConfig/DynamicCorsFilter) covers the /higher/health/facility base path for all HTTP methods and handles preflight requests.


67-67: Removed method-level @CrossOrigin annotation.
Confirm that the dynamic CORS filter correctly applies to the /get/clinical/data endpoint, including OPTIONS preflight handling and header allowances.

src/main/java/com/wipro/fhir/controller/healthID/CreateHealthIdRecord.java (3)

19-19: Removed class-level @CrossOrigin annotation.
Verify that the centralized CORS policy applies to the /healthIDRecord controller and that no endpoints are inadvertently blocked.


35-35: Removed method-level @CrossOrigin annotation on mapHealthIDToBeneficiary.
Ensure the global filter covers /healthIDRecord/mapHealthIDToBeneficiary, including CORS preflight and header propagation.


57-57: Removed method-level @CrossOrigin annotation on addHealthIdRecord.
Confirm that /healthIDRecord/addHealthIdRecord is included in your centralized CORS configuration, handling both actual requests and preflight checks.

src/main/java/com/wipro/fhir/controller/healthIDvalidate/HealthIDValidateController.java (1)

41-94:

Details

✅ Verification successful

Verify centralized CORS configuration is working properly.

The systematic removal of @CrossOrigin annotations from the class and methods is well-executed as part of centralizing CORS management. Ensure that the new centralized CORS configuration properly handles cross-origin requests for all endpoints in this controller.


🏁 Script executed:

#!/bin/bash
# Description: Verify that centralized CORS configuration exists and is properly configured

# Check for CorsConfig class
fd -t f "CorsConfig.java" | head -5

# Check for CORS configuration properties
fd -t f -e properties | xargs grep -l "cors.allowed-origins" 2>/dev/null

# Check for DynamicCorsFilter
fd -t f "DynamicCorsFilter.java" | head -5

Length of output: 338


🏁 Script executed:

#!/bin/bash
# Display the central CORS configuration to verify global mappings
echo "+++ CorsConfig.java +++"
sed -n '1,200p' src/main/java/com/wipro/fhir/config/CorsConfig.java
echo ""
echo "+++ DynamicCorsFilter.java +++"
sed -n '1,200p' src/main/java/com/wipro/fhir/utils/DynamicCorsFilter.java

Length of output: 2450


Centralized CORS configuration covers all controller endpoints

Your global CORS setup in CorsConfig (registry.addMapping("/**")…) and the DynamicCorsFilter both apply to every endpoint—including those in HealthIDValidateController—so you can safely remove all method-level @crossorigin annotations.
No further changes are needed.

src/main/java/com/wipro/fhir/controller/carecontext/CareContextController.java (1)

41-113: LGTM! Systematic CORS annotation removal.

The removal of @CrossOrigin annotations from class and method levels is consistent with the centralized CORS configuration approach. The controller logic remains intact.

src/main/java/com/wipro/fhir/controller/healthID/CreateHealthIDWithMobileOTP.java (1)

43-169: LGTM! Complete CORS annotation removal.

All @CrossOrigin annotations have been systematically removed from the class and all endpoint methods. The controller functionality remains unchanged, and this aligns with the centralized CORS configuration approach.

src/main/java/com/wipro/fhir/controller/generateresource/ResourceRequestGateway.java (1)

52-147:

Details

✅ Verification successful

Excellent! Complete CORS refactoring.

The systematic removal of all @CrossOrigin annotations from class and method levels is well-executed. This completes the centralization of CORS configuration for this controller.


🏁 Script executed:

#!/bin/bash
# Description: Verify that CORS refactoring is complete across the entire codebase

# Check for any remaining @CrossOrigin annotations in controllers
rg -A 2 -B 2 "@CrossOrigin" --type java src/

# Verify centralized CORS configuration files exist
echo "=== Checking for CorsConfig class ==="
fd "CorsConfig.java" src/ | xargs cat 2>/dev/null || echo "CorsConfig.java not found"

echo "=== Checking for DynamicCorsFilter class ==="
fd "DynamicCorsFilter.java" src/ | xargs cat 2>/dev/null || echo "DynamicCorsFilter.java not found"

echo "=== Checking CORS properties ==="
fd -e properties src/ | xargs grep "cors" 2>/dev/null || echo "No CORS properties found"

Length of output: 2979


🏁 Script executed:

#!/bin/bash
# Verify that the required CORS property definitions are present

echo "=== Searching for 'cors.allowed-origins' across the repository ==="
rg -n "cors.allowed-origins" .

echo "=== Searching for any 'cors' entries in .properties/.yml/.yaml files ==="
rg -n "cors" --glob "*.properties" --glob "*.yml" --glob "*.yaml" .

Length of output: 1200


CORS Refactoring Complete: Centralized Configuration Verified

  • No @CrossOrigin annotations remain in any controller.
  • CorsConfig.java and DynamicCorsFilter.java are present and correctly configured.
  • The cors.allowed-origins property is defined in common_example.properties and common_ci.properties.
src/main/java/com/wipro/fhir/controller/v3/abha/LoginAbhaV3Controller.java (1)

18-18: Verify central CORS configuration applies correctly to this controller

Per-controller @CrossOrigin annotations were removed in favor of a global CORS setup (CorsConfig and DynamicCorsFilter), which is appropriate. Please ensure that requests to /abhaLogin endpoints (including preflight OPTIONS) correctly include the configured CORS headers. Add integration tests or use tooling (e.g., curl or browser devtools) to confirm the allowed origins and methods are applied as expected.

Also applies to: 28-28, 48-48

src/main/java/com/wipro/fhir/controller/healthID/CreateHealthIDWithBio.java (1)

20-20: Validate global CORS handling for bio-based health ID endpoints

The removal of method-level @CrossOrigin annotations is intentional to centralize CORS. Ensure that the /healthIDWithBio endpoints (verifyBio, generateMobileOTP, confirmWithAadhaarBio) are still reachable from the configured origins and properly support preflight OPTIONS requests under the new DynamicCorsFilter and CorsConfig.

Also applies to: 53-53, 75-75

src/main/java/com/wipro/fhir/controller/facility/FacilityController.java (1)

23-23: Confirm removal of @crossorigin is covered by global CORS config

Controller- and method-level @CrossOrigin annotations were removed. Please verify that the global CORS settings (in CorsConfig) correctly apply to /facility endpoints (getAbdmRegisteredFacilities and saveAbdmFacilityId), including allowing the necessary HTTP methods and handling OPTIONS preflight.

Also applies to: 34-34, 57-57

src/main/java/com/wipro/fhir/controller/eaushdhi/EAushadhiController.java (1)

50-50: Ensure central CORS filter manages all eAushadhi endpoints

All @CrossOrigin annotations were stripped to enforce centralized settings. Double-check that DynamicCorsFilter (and CorsConfig) correctly set the necessary headers for the /eAushadhi endpoints (getStoreStockDetails, syncDrugDispenseDetails, getFacilityStockProcessLog, updatePatientIssueSyncStatus), including preflight responses.

Also applies to: 59-59, 93-93, 116-116

src/main/java/com/wipro/fhir/controller/healthID/CreateHealthIDWithUID.java (1)

41-41: Validate global CORS coverage for UID-based health ID API

Method- and class-level @CrossOrigin annotations were removed for /healthIDWithUID. Confirm that the centralized CORS setup covers all operations (generateOTP, verifyOTP, checkAndGenerateMobileOTP, verifyMobileOTP, createHealthIDWithUID) and that OPTIONS preflight requests succeed for allowed origins.

Also applies to: 73-73, 96-96, 120-120, 144-144

src/main/java/com/wipro/fhir/config/CorsConfig.java (1)

11-12:

Details

❓ Verification inconclusive

Verify CORS allowed origins property configuration.

The configuration reads from cors.allowed-origins property. Ensure this property is properly configured in all environments to prevent security vulnerabilities.


🏁 Script executed:

#!/bin/bash
# Description: Verify that cors.allowed-origins property is defined in configuration files
# Expected: Property should be found in environment configuration files

echo "Searching for cors.allowed-origins property definition..."
fd -e properties . --exec grep -l "cors.allowed-origins" {}

echo -e "\nShowing property values:"
fd -e properties . --exec grep "cors.allowed-origins" {}

Length of output: 487


Confirm CORS allowed-origins property definitions across all environments

The cors.allowed-origins property is currently defined in:

  • src/main/environment/common_example.propertiescors.allowed-origins=@CORS_ALLOWED_ORIGINS@
  • src/main/environment/common_ci.propertiescors.allowed-origins=http://localhost:*

Please ensure:

  • The @CORS_ALLOWED_ORIGINS@ placeholder is replaced with a restricted, explicit list of origins in each deployment environment (dev, staging, prod).
  • No environment relies on overly broad patterns (e.g., wildcards) that could inadvertently expose the API.
  • Environment-specific property files or variables properly override the example/CI defaults.
src/main/java/com/wipro/fhir/controller/v3/abha/CreateAbhaV3Controller.java (1)

18-89: Verify that global CORS configuration covers all endpoints.

The removal of @CrossOrigin annotations from this controller is part of centralizing CORS configuration. Ensure that the new global CORS configuration in CorsConfig.java provides the same level of access for all endpoints that previously had individual annotations.

Based on the retrieved learning, this change breaks the previous consistency of using @CrossOrigin annotations across controllers, but this is intentional as part of the centralization effort.

src/main/java/com/wipro/fhir/utils/FilterConfig.java (2)

12-13: LGTM: Proper injection of CORS configuration.

The addition of @Value annotation to inject the cors.allowed-origins property is correctly implemented.


20-21:

Details

✅ Verification successful

Verify JwtUserIdValidationFilter constructor supports allowedOrigins parameter.

The filter instantiation now passes allowedOrigins to the constructor. Ensure that JwtUserIdValidationFilter has been updated to accept this parameter and handle CORS appropriately.


🏁 Script executed:

#!/bin/bash
# Description: Verify JwtUserIdValidationFilter constructor accepts allowedOrigins parameter
# Expected: Constructor should accept (JwtAuthenticationUtil, String) parameters

echo "Searching for JwtUserIdValidationFilter constructor..."
ast-grep --pattern 'class JwtUserIdValidationFilter {
  $$$
  public JwtUserIdValidationFilter($_, $_) {
    $$$
  }
  $$$
}'

Length of output: 246


🏁 Script executed:

#!/bin/bash
echo "Locating JwtUserIdValidationFilter file..."
fd JwtUserIdValidationFilter.java

echo "Searching for constructor declarations in JwtUserIdValidationFilter..."
rg -n "public class JwtUserIdValidationFilter" .
rg -n "JwtUserIdValidationFilter(" .

Length of output: 670


🏁 Script executed:

#!/bin/bash
echo "Listing constructors in JwtUserIdValidationFilter..."
rg -n "public JwtUserIdValidationFilter" src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java || true

echo "Checking for allowedOrigins usage in constructors or fields..."
rg -n "allowedOrigins" src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java || true

Length of output: 839


Confirmed: JwtUserIdValidationFilter supports allowedOrigins parameter

The constructor in src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java now declares

public JwtUserIdValidationFilter(
    JwtAuthenticationUtil jwtAuthenticationUtil,
    @Value("${cors.allowed-origins}") String allowedOrigins
) { … }

and assigns allowedOrigins to the corresponding field. The filter’s CORS logic (lines 126–131) correctly checks and splits this value. No further changes required.

src/main/java/com/wipro/fhir/controller/healthCard/GenerateHealthIDCardController.java (1)

41-71: LGTM: Consistent with CORS centralization effort.

The removal of @CrossOrigin annotations from class and method levels is consistent with the centralized CORS configuration approach implemented in CorsConfig.java. The controller functionality remains unchanged.

src/main/java/com/wipro/fhir/controller/patientdatahandler/PatientDataGatewayController.java (1)

44-75: LGTM: @crossorigin annotations successfully removed for centralized CORS configuration.

The removal of @CrossOrigin annotations from this controller aligns with the PR objective to centralize CORS handling through the new DynamicCorsFilter and enhanced JwtUserIdValidationFilter. This approach provides better maintainability and consistent CORS policy across the application.

src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java (3)

29-33: LGTM: Constructor properly enhanced for CORS support.

The constructor correctly accepts the allowedOrigins configuration parameter and stores it for use in CORS validation.


46-58: LGTM: Proper CORS header handling and OPTIONS support.

The CORS header implementation correctly:

  • Validates origins using the isOriginAllowed method
  • Sets comprehensive CORS headers including credentials support
  • Handles OPTIONS preflight requests appropriately
  • Logs the OPTIONS request handling for debugging

125-133: LGTM: Robust origin validation with wildcard support.

The isOriginAllowed method properly:

  • Handles null/empty checks
  • Supports comma-separated origins
  • Implements wildcard pattern matching with proper regex escaping
  • Includes appropriate logging for debugging

Comment on lines +16 to +23
registry.addMapping("/**")
.allowedOriginPatterns(allowedOrigins.split(","))
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*")
.exposedHeaders("Authorization", "Jwttoken") // Explicitly expose headers if needed
.allowCredentials(true)
.maxAge(3600)
;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Address security concerns in CORS configuration.

The current CORS configuration has several security concerns:

  1. String splitting without trimming: allowedOrigins.split(",") doesn't handle whitespace, which could lead to unexpected behavior.
  2. Overly permissive headers: Using allowedHeaders("*") allows all headers, which might be too broad.
  3. Credentials with patterns: Using allowCredentials(true) with allowedOriginPatterns can be risky if the patterns are too broad.

Apply this diff to improve security:

-        registry.addMapping("/**")
-				.allowedOriginPatterns(allowedOrigins.split(","))
-                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
-                .allowedHeaders("*")
-                .exposedHeaders("Authorization", "Jwttoken") // Explicitly expose headers if needed
-                .allowCredentials(true)
-                .maxAge(3600)
-                ;
+        String[] origins = allowedOrigins.split(",");
+        for (int i = 0; i < origins.length; i++) {
+            origins[i] = origins[i].trim();
+        }
+        
+        registry.addMapping("/**")
+                .allowedOriginPatterns(origins)
+                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
+                .allowedHeaders("Content-Type", "Authorization", "X-Requested-With", "Accept", "Origin")
+                .exposedHeaders("Authorization", "Jwttoken")
+                .allowCredentials(true)
+                .maxAge(3600);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
registry.addMapping("/**")
.allowedOriginPatterns(allowedOrigins.split(","))
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*")
.exposedHeaders("Authorization", "Jwttoken") // Explicitly expose headers if needed
.allowCredentials(true)
.maxAge(3600)
;
String[] origins = allowedOrigins.split(",");
for (int i = 0; i < origins.length; i++) {
origins[i] = origins[i].trim();
}
registry.addMapping("/**")
.allowedOriginPatterns(origins)
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("Content-Type", "Authorization", "X-Requested-With", "Accept", "Origin")
.exposedHeaders("Authorization", "Jwttoken")
.allowCredentials(true)
.maxAge(3600);
🤖 Prompt for AI Agents
In src/main/java/com/wipro/fhir/config/CorsConfig.java around lines 16 to 23,
improve CORS security by trimming whitespace from each origin after splitting
allowedOrigins by commas, replacing allowedHeaders("*") with a specific list of
allowed headers instead of all headers, and ensure that allowCredentials(true)
is only used if allowedOriginPatterns are strictly defined and not overly broad
to prevent security risks.

Comment on lines +26 to +29
String origin = request.getHeader("Origin");
if (origin != null && Arrays.asList(allowedOrigins).contains(origin)) {
response.setHeader("Access-Control-Allow-Origin", origin);
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improve origin validation with wildcard support and null safety.

The current exact string matching doesn't support wildcard patterns and lacks null safety checks.

-String origin = request.getHeader("Origin");
-if (origin != null && Arrays.asList(allowedOrigins).contains(origin)) {
-    response.setHeader("Access-Control-Allow-Origin", origin);
-}
+String origin = request.getHeader("Origin");
+if (origin != null && isOriginAllowed(origin)) {
+    response.setHeader("Access-Control-Allow-Origin", origin);
+}

Add the helper method:

private boolean isOriginAllowed(String origin) {
    if (origin == null || allowedOrigins == null || allowedOrigins.trim().isEmpty()) {
        return false;
    }
    return Arrays.stream(allowedOrigins.split(","))
            .map(String::trim)
            .anyMatch(pattern -> origin.matches(pattern.replace(".", "\\.").replace("*", ".*")));
}
🤖 Prompt for AI Agents
In src/main/java/com/wipro/fhir/utils/DynamicCorsFilter.java around lines 26 to
29, the origin validation currently uses exact string matching without null
safety or wildcard support. To fix this, add a helper method isOriginAllowed
that checks if the origin is null or empty and then matches it against
allowedOrigins patterns supporting wildcards by converting them to regex.
Replace the existing origin check with a call to this method to improve
validation robustness and flexibility.

Comment on lines +17 to +18
@Value("${cors.allowed-origins}")
private String[] allowedOrigins;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Configuration type inconsistency with JwtUserIdValidationFilter.

The allowedOrigins is declared as String[] here, but in JwtUserIdValidationFilter it's declared as String. This inconsistency could lead to configuration binding issues.

Ensure consistent configuration property types across all filters:

-@Value("${cors.allowed-origins}")
-private String[] allowedOrigins;
+@Value("${cors.allowed-origins}")
+private String allowedOrigins;

Then update the origin checking logic to split the string:

-if (origin != null && Arrays.asList(allowedOrigins).contains(origin)) {
+if (origin != null && isOriginAllowed(origin)) {

Add the isOriginAllowed method similar to JwtUserIdValidationFilter.

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In src/main/java/com/wipro/fhir/utils/DynamicCorsFilter.java around lines 17 to
18, the allowedOrigins field is declared as String[], but in
JwtUserIdValidationFilter it is a single String, causing configuration binding
inconsistency. Change allowedOrigins to a single String to match
JwtUserIdValidationFilter, then update the origin checking logic to split this
string into an array or list before use. Also, add an isOriginAllowed method
similar to the one in JwtUserIdValidationFilter to handle origin validation
consistently.

Comment on lines +31 to +35
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
filterChain.doFilter(request, response);
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

OPTIONS preflight requests missing CORS headers.

For OPTIONS requests, the filter returns 200 OK but doesn't set the necessary CORS headers that browsers expect for preflight requests.

 if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
+    String origin = request.getHeader("Origin");
+    if (origin != null && isOriginAllowed(origin)) {
+        response.setHeader("Access-Control-Allow-Origin", origin);
+        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
+        response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, Accept, Jwttoken");
+        response.setHeader("Access-Control-Allow-Credentials", "true");
+        response.setHeader("Access-Control-Max-Age", "3600");
+    }
     response.setStatus(HttpServletResponse.SC_OK);
 } else {
     filterChain.doFilter(request, response);
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
filterChain.doFilter(request, response);
}
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
String origin = request.getHeader("Origin");
if (origin != null && isOriginAllowed(origin)) {
response.setHeader("Access-Control-Allow-Origin", origin);
response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, Accept, Jwttoken");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Max-Age", "3600");
}
response.setStatus(HttpServletResponse.SC_OK);
} else {
filterChain.doFilter(request, response);
}
🤖 Prompt for AI Agents
In src/main/java/com/wipro/fhir/utils/DynamicCorsFilter.java around lines 31 to
35, the code handles OPTIONS requests by setting the status to 200 OK but does
not set the required CORS headers. To fix this, ensure that before setting the
status for OPTIONS requests, you add the necessary CORS headers to the response,
such as Access-Control-Allow-Origin, Access-Control-Allow-Methods, and
Access-Control-Allow-Headers, so that browsers receive the expected headers
during preflight checks.

Comment on lines +14 to +37
@Component
public class DynamicCorsFilter extends OncePerRequestFilter {

@Value("${cors.allowed-origins}")
private String[] allowedOrigins;

@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain)
throws ServletException, IOException {

String origin = request.getHeader("Origin");
if (origin != null && Arrays.asList(allowedOrigins).contains(origin)) {
response.setHeader("Access-Control-Allow-Origin", origin);
}

if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
filterChain.doFilter(request, response);
}
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Consider potential filter conflict with JwtUserIdValidationFilter.

Both DynamicCorsFilter and JwtUserIdValidationFilter are setting CORS headers, which could lead to conflicts or duplicate headers.

Verify the filter ordering and ensure only one filter handles CORS to avoid conflicts:


🏁 Script executed:

#!/bin/bash
# Check filter registration order and CORS header handling
ast-grep --pattern 'class $_ implements Filter'
ast-grep --pattern 'class $_ extends OncePerRequestFilter'
rg -A 5 "setHeader.*Access-Control"
rg -A 3 "@Component.*Filter"

Length of output: 2399


Centralize CORS handling and remove duplicate headers

I’ve identified three places where CORS headers are being set:

  • src/main/java/com/wipro/fhir/utils/DynamicCorsFilter.java
  • src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java
  • src/main/java/com/wipro/fhir/utils/http/HTTPRequestInterceptor.java

To avoid conflicts or duplicate headers:

• Consolidate all CORS logic into a single filter (e.g. DynamicCorsFilter).
• Remove or disable any response.setHeader("Access-Control-…") calls from JwtUserIdValidationFilter and HTTPRequestInterceptor.
• Ensure your CORS filter runs first by giving it highest precedence. For example:

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class DynamicCorsFilter extends OncePerRequestFilter {
    // …
}

Or register it explicitly:

@Bean
public FilterRegistrationBean<DynamicCorsFilter> corsFilterRegistration() {
    FilterRegistrationBean<DynamicCorsFilter> reg = new FilterRegistrationBean<>(new DynamicCorsFilter());
    reg.setOrder(Ordered.HIGHEST_PRECEDENCE);
    return reg;
}

This will guarantee only one component sets CORS headers and in the correct order.

🤖 Prompt for AI Agents
In src/main/java/com/wipro/fhir/utils/DynamicCorsFilter.java around lines 14 to
37, the CORS headers are set here but also in JwtUserIdValidationFilter and
HTTPRequestInterceptor, causing potential conflicts or duplicate headers. To fix
this, centralize all CORS handling in DynamicCorsFilter by removing or disabling
any response.setHeader("Access-Control-…") calls in JwtUserIdValidationFilter
and HTTPRequestInterceptor. Additionally, ensure DynamicCorsFilter runs first by
adding @Order(Ordered.HIGHEST_PRECEDENCE) annotation or registering it with
FilterRegistrationBean and setting its order to highest precedence.


private final JwtAuthenticationUtil jwtAuthenticationUtil;
private final Logger logger = LoggerFactory.getLogger(this.getClass().getName());
private final String allowedOrigins;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Verify configuration property type consistency.

Ensure the cors.allowed-origins property type is consistent with DynamicCorsFilter which expects String[].

Check the configuration property definition and binding:


🏁 Script executed:

#!/bin/bash
# Check property definitions and usage
rg -A 2 -B 2 "cors.allowed-origins"
ast-grep --pattern '@Value("${cors.allowed-origins}") String $_'
ast-groove --pattern '@Value("${cors.allowed-origins}") String[] $_'

Length of output: 2549


Unify cors.allowed-origins binding across all filters

We currently inject the same property as both String and String[], which can lead to binding inconsistencies. To align with DynamicCorsFilter (which expects String[]), update the other classes to use String[] as well:

• src/main/java/com/wipro/fhir/utils/FilterConfig.java
• src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java
• src/main/java/com/wipro/fhir/config/CorsConfig.java

Example diff (apply in all three files):

 @Value("${cors.allowed-origins}")
- private String allowedOrigins;
+ private String[] allowedOrigins;

And in JwtUserIdValidationFilter’s constructor:

- public JwtUserIdValidationFilter(..., @Value("${cors.allowed-origins}") String allowedOrigins) {
+ public JwtUserIdValidationFilter(..., @Value("${cors.allowed-origins}") String[] allowedOrigins) {

This ensures Spring binds comma-separated origins correctly everywhere.

🤖 Prompt for AI Agents
In src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java at line 27,
the allowedOrigins field is declared as a String but should be a String array to
match the expected type in DynamicCorsFilter and maintain consistency across
filters. Change the type of allowedOrigins from String to String[] and update
the constructor and any related code to handle a String array. This will ensure
Spring correctly binds the comma-separated origins property uniformly.

@vishwab1 vishwab1 closed this Jun 17, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants